diff --git a/.circleci/config.yml b/.circleci/config.yml index 5e3e4d8c4..437fb1c87 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -30,6 +30,7 @@ jobs: # fallback to using the latest cache if no exact match is found - v1-dependencies- + - run: mvn dependency:go-offline - save_cache: diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 000000000..e76d1f324 --- /dev/null +++ b/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,117 @@ +/* + * Copyright 2007-present the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.6"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/HELP.md b/HELP.md new file mode 100644 index 000000000..ee42ad0d4 --- /dev/null +++ b/HELP.md @@ -0,0 +1,9 @@ +# Getting Started + +### Reference Documentation +For further reference, please consider the following sections: + +* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html) +* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/2.4.0/maven-plugin/reference/html/) +* [Create an OCI image](https://docs.spring.io/spring-boot/docs/2.4.0/maven-plugin/reference/html/#build-image) + diff --git a/pom.xml b/pom.xml index fba1a29a1..b22c1bd9f 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,11 @@ guru.springfamework spring5-mvc-rest 0.0.1-SNAPSHOT - jar + + rest-model + spring5-mvc-rest-app + + pom spring5-mvc-rest Demo project for Spring Boot @@ -14,7 +18,7 @@ org.springframework.boot spring-boot-starter-parent - 2.1.0.RELEASE + 2.3.6.RELEASE @@ -22,67 +26,11 @@ UTF-8 UTF-8 1.8 + 2.7.0 - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework.boot - spring-boot-devtools - runtime - - - com.h2database - h2 - runtime - - - org.projectlombok - lombok - true - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - org.codehaus.mojo - cobertura-maven-plugin - 2.7 - - - html - xml - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.1 - - false - - - - + diff --git a/rest-model/pom.xml b/rest-model/pom.xml new file mode 100644 index 000000000..476156773 --- /dev/null +++ b/rest-model/pom.xml @@ -0,0 +1,56 @@ + + + + spring5-mvc-rest + guru.springfamework + 0.0.1-SNAPSHOT + + 4.0.0 + + rest-model + spring-rest-model + + + javax.xml.bind + jaxb-api + 2.3.0 + + + com.sun.xml.bind + jaxb-core + 2.3.0 + + + com.sun.xml.bind + jaxb-impl + 2.3.0 + + + + + + org.codehaus.mojo + jaxb2-maven-plugin + 2.5.0 + + + xjc + + xjc + + + + + + guru.springfamework.model + + src/main/resources/xsd + + + + + + + \ No newline at end of file diff --git a/spring5-mvc-rest-app/pom.xml b/spring5-mvc-rest-app/pom.xml new file mode 100644 index 000000000..921042f20 --- /dev/null +++ b/spring5-mvc-rest-app/pom.xml @@ -0,0 +1,128 @@ + + + + spring5-mvc-rest + guru.springfamework + 0.0.1-SNAPSHOT + + 4.0.0 + + spring5-mvc-rest-app + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-devtools + runtime + + + com.h2database + h2 + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.mapstruct + mapstruct + 1.4.1.Final + + + io.springfox + springfox-swagger2 + ${springfox-swagger-version} + + + io.springfox + springfox-swagger-ui + ${springfox-swagger-version} + + + org.codehaus.woodstox + woodstox-core-asl + 4.4.1 + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + + + guru.springfamework + rest-model + 0.0.1-SNAPSHOT + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.codehaus.mojo + cobertura-maven-plugin + 2.7 + + + html + xml + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.1 + + false + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + 1.8 + 1.8 + + + org.projectlombok + lombok + ${lombok.version} + + + org.mapstruct + mapstruct-processor + 1.4.1.Final + + + + + -Amapstruct.defaultComponentModel=spring + + + + + + + + \ No newline at end of file diff --git a/src/main/java/guru/springfamework/Spring5MvcRestApplication.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/Spring5MvcRestApplication.java similarity index 86% rename from src/main/java/guru/springfamework/Spring5MvcRestApplication.java rename to spring5-mvc-rest-app/src/main/java/guru/springfamework/Spring5MvcRestApplication.java index dabeae054..3cdd0d308 100644 --- a/src/main/java/guru/springfamework/Spring5MvcRestApplication.java +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/Spring5MvcRestApplication.java @@ -4,9 +4,12 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication -public class Spring5MvcRestApplication { + +public class Spring5MvcRestApplication { public static void main(String[] args) { SpringApplication.run(Spring5MvcRestApplication.class, args); } + + } diff --git a/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/mapper/CategoryMapper.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/mapper/CategoryMapper.java new file mode 100644 index 000000000..306a2caf1 --- /dev/null +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/mapper/CategoryMapper.java @@ -0,0 +1,21 @@ +package guru.springfamework.api.v1.mapper; + + +import guru.springfamework.api.v1.model.CategoryDTO; +import guru.springfamework.domain.Category; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +/** + * Darcy Xian 21/11/20 12:37 pm spring5-mvc-rest + */ +@Mapper +public interface CategoryMapper { + + CategoryMapper INSTANCE = Mappers.getMapper(CategoryMapper.class); + + @Mapping(source = "id", target = "id") + CategoryDTO categoryToCategoryDTO(Category category); + +} diff --git a/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/mapper/CustomerMapper.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/mapper/CustomerMapper.java new file mode 100644 index 000000000..32a0b1cc2 --- /dev/null +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/mapper/CustomerMapper.java @@ -0,0 +1,24 @@ +package guru.springfamework.api.v1.mapper; + + +import guru.springfamework.domain.Customer; +import guru.springfamework.model.CustomerDTO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +/** + * Darcy Xian 22/11/20 4:51 pm spring5-mvc-rest + */ +@Mapper +public interface CustomerMapper { + + CustomerMapper INSTANCE = Mappers.getMapper(CustomerMapper.class); + + @Mapping(source = "id",target = "id") + CustomerDTO CustomerToCustomerDTO(Customer customer); + + @Mapping(source = "id",target = "id") + Customer CustomerDTOToCustomer(CustomerDTO customerDTO); + +} diff --git a/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/mapper/VendorMapper.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/mapper/VendorMapper.java new file mode 100644 index 000000000..ead9a175d --- /dev/null +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/mapper/VendorMapper.java @@ -0,0 +1,25 @@ +package guru.springfamework.api.v1.mapper; + +import guru.springfamework.api.v1.model.VendorDTO; +import guru.springfamework.domain.Vendor; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + + +/** + * Darcy Xian 24/11/20 3:36 pm spring5-mvc-rest + */ +@Mapper +public interface VendorMapper { + + VendorMapper INSTANCE = Mappers.getMapper(VendorMapper.class); + + @Mapping(source = "id", target = "id") + VendorDTO vendorToVendorDTO(Vendor vendor); + + @Mapping(source = "id", target = "id") + Vendor vendorDTOToVendor(VendorDTO vendorDTO); + + +} diff --git a/src/main/java/guru/springfamework/api/v1/model/CategoryDTO.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/model/CategoryDTO.java similarity index 85% rename from src/main/java/guru/springfamework/api/v1/model/CategoryDTO.java rename to spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/model/CategoryDTO.java index 135ca3621..94c0ecb7b 100644 --- a/src/main/java/guru/springfamework/api/v1/model/CategoryDTO.java +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/model/CategoryDTO.java @@ -1,8 +1,11 @@ package guru.springfamework.api.v1.model; +import lombok.Data; + /** * Created by jt on 9/24/17. */ +@Data public class CategoryDTO { private Long id; private String name; diff --git a/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/model/CategoryListDTO.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/model/CategoryListDTO.java new file mode 100644 index 000000000..b42d632b1 --- /dev/null +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/model/CategoryListDTO.java @@ -0,0 +1,15 @@ +package guru.springfamework.api.v1.model; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import java.util.List; + +/** + * Darcy Xian 21/11/20 7:42 pm spring5-mvc-rest + */ +@Data +@AllArgsConstructor +public class CategoryListDTO { + List categoryListDTOS; +} diff --git a/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/model/CustomerDTO.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/model/CustomerDTO.java new file mode 100644 index 000000000..fe77f21a3 --- /dev/null +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/model/CustomerDTO.java @@ -0,0 +1,18 @@ +package guru.springfamework.api.v1.model; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +/** + * Darcy Xian 22/11/20 4:46 pm spring5-mvc-rest + */ +@Data +public class CustomerDTO { + + private Long id; + @ApiModelProperty(value = "This is the first name",required = true) + private String firstname; + @ApiModelProperty(value = "This is the first name",required = false) + private String lastname; + private String customerUrl; +} diff --git a/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/model/CustomerListDTO.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/model/CustomerListDTO.java new file mode 100644 index 000000000..305b32ddd --- /dev/null +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/model/CustomerListDTO.java @@ -0,0 +1,18 @@ +package guru.springfamework.api.v1.model; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +/** + * Darcy Xian 22/11/20 4:47 pm spring5-mvc-rest + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +public class CustomerListDTO { + + List customerListDTOS; +} diff --git a/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/model/VendorDTO.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/model/VendorDTO.java new file mode 100644 index 000000000..fa3a32e4e --- /dev/null +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/model/VendorDTO.java @@ -0,0 +1,21 @@ +package guru.springfamework.api.v1.model; + +import lombok.Data; + +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +/** + * Darcy Xian 24/11/20 3:30 pm spring5-mvc-rest + */ +@Data +public class VendorDTO { + + + private Long id; + private String name; + private String nickName; + private String vendorUrl; + +} diff --git a/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/model/VendorListDTO.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/model/VendorListDTO.java new file mode 100644 index 000000000..f649301d9 --- /dev/null +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/api/v1/model/VendorListDTO.java @@ -0,0 +1,13 @@ + +package guru.springfamework.api.v1.model; + +import lombok.AllArgsConstructor; +import lombok.Data; +import java.util.List; + +@Data +@AllArgsConstructor +public class VendorListDTO +{ + List vendorDTOS; +} diff --git a/spring5-mvc-rest-app/src/main/java/guru/springfamework/bootstrap/Bootstrap.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/bootstrap/Bootstrap.java new file mode 100644 index 000000000..acec4186a --- /dev/null +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/bootstrap/Bootstrap.java @@ -0,0 +1,88 @@ +package guru.springfamework.bootstrap; + +import guru.springfamework.domain.Category; +import guru.springfamework.domain.Customer; +import guru.springfamework.domain.Vendor; +import guru.springfamework.repositories.CategoryRepository; +import guru.springfamework.repositories.CustomerRepository; +import guru.springfamework.repositories.VendorRepository; +import lombok.AllArgsConstructor; +import org.springframework.boot.CommandLineRunner; +import org.springframework.stereotype.Component; + +/** + * Darcy Xian 21/11/20 11:25 am spring5-mvc-rest + */ +@Component +@AllArgsConstructor +public class Bootstrap implements CommandLineRunner { + private CategoryRepository categoryRepository; + private CustomerRepository customerRepository; + private VendorRepository vendorRepository; + + + @Override + public void run(String... args) throws Exception { + loadCategories(); + loadCustomers(); + loadVendors(); + + } + + private void loadCategories() { + // for category + Category fruits = new Category(); + fruits.setName("Fruits"); + + Category dried = new Category(); + dried.setName("Dried"); + + Category fresh = new Category(); + fresh.setName("Fresh"); + + Category exotic = new Category(); + exotic.setName("Exotic"); + + Category nuts = new Category(); + nuts.setName("nuts"); + + categoryRepository.save(fruits); + categoryRepository.save(dried); + categoryRepository.save(fresh); + categoryRepository.save(exotic); + categoryRepository.save(nuts); + + System.out.println("Data Loaded = " + categoryRepository.count()); + } + + private void loadCustomers(){ + // for Customer + Customer customer = new Customer(); + customer.setFirstname("Lin"); + customer.setLastname("Ken"); + + Customer customer1 = new Customer(); + customer1.setFirstname("Jerry"); + customer1.setLastname("Joe"); + + customerRepository.save(customer1); + customerRepository.save(customer); + System.out.println("Customers Loaded = " + customerRepository.count()); + } + + private void loadVendors(){ + Vendor vendor = new Vendor(); + vendor.setName("Nike"); + vendor.setNickName("ccccc"); + + Vendor vendor1 = new Vendor(); + vendor1.setName("Addidass"); + vendor1.setNickName("kkkkkk"); + + vendorRepository.save(vendor); + vendorRepository.save(vendor1); + System.out.println("Vendors Loaded = " + vendorRepository.count()); + + + } +} diff --git a/spring5-mvc-rest-app/src/main/java/guru/springfamework/config/SwaggerConfig.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/config/SwaggerConfig.java new file mode 100644 index 000000000..bc5a6d590 --- /dev/null +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/config/SwaggerConfig.java @@ -0,0 +1,58 @@ +package guru.springfamework.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +import java.util.ArrayList; + +/** + * Darcy Xian 25/11/20 9:58 am spring5-mvc-rest + */ +@EnableSwagger2 +@Configuration + +public class SwaggerConfig extends WebMvcConfigurationSupport { + @Bean + public Docket api(){ + return new Docket(DocumentationType.SWAGGER_2) + .select().apis(RequestHandlerSelectors.basePackage("guru.springfamework.controllers.v1")) + .paths(PathSelectors.any()) + .build() + .pathMapping("/") + .apiInfo(metaData()); + } + @Override + protected void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/swagger-ui.html") + .addResourceLocations("classpath:/META-INF/resources/"); + + registry.addResourceHandler("/webjars/**") + .addResourceLocations("classpath:/META-INF/resources/webjars/"); + } + private ApiInfo metaData(){ + Contact contact = new Contact("Darcy Xian","http","asdfadf@gmail.com"); + + return new ApiInfo( + "Spring Framework Darcy", + "Spring Framework 5", + "1.0", + "terms of service: blah", + contact, + "Apache License Version 2.0", + "https://www.apache.org/licenses/LICENSE-2.0", + new ArrayList<>()); + + + } + +} diff --git a/spring5-mvc-rest-app/src/main/java/guru/springfamework/controllers/v1/CategoryController.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/controllers/v1/CategoryController.java new file mode 100644 index 000000000..fed9b2904 --- /dev/null +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/controllers/v1/CategoryController.java @@ -0,0 +1,35 @@ +package guru.springfamework.controllers.v1; + +import guru.springfamework.services.CategoryService; +import guru.springfamework.api.v1.model.CategoryDTO; +import guru.springfamework.api.v1.model.CategoryListDTO; +import lombok.AllArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.*; + +/** + * Darcy Xian 21/11/20 7:37 pm spring5-mvc-rest + */ +@RestController +@RequestMapping(CategoryController.BASE_URL) +@AllArgsConstructor +public class CategoryController { + + public static final String BASE_URL = "/api/v1/categories/"; + + private final CategoryService categoryService; + + + @GetMapping + @ResponseStatus(HttpStatus.OK) + public CategoryListDTO getAllCategories(){ + return new CategoryListDTO(categoryService.getAllCategories()); + } + @GetMapping("{name}") + @ResponseStatus(HttpStatus.OK) + public CategoryDTO getCategoryByName (@PathVariable String name){ + return categoryService.getCategoryByName(name); + } + + +} diff --git a/spring5-mvc-rest-app/src/main/java/guru/springfamework/controllers/v1/CustomerController.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/controllers/v1/CustomerController.java new file mode 100644 index 000000000..26c205e84 --- /dev/null +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/controllers/v1/CustomerController.java @@ -0,0 +1,142 @@ +package guru.springfamework.controllers.v1; + + +import guru.springfamework.model.CustomerDTO; +import guru.springfamework.model.CustomerListDTO; +import guru.springfamework.services.CustomerService; + + + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.AllArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.*; + +/** + * Darcy Xian 22/11/20 5:05 pm spring5-mvc-rest + */ +@Api(description = "This is my Customer controller") +@RestController +@RequestMapping(CustomerController.BASE_URL) +@AllArgsConstructor +public class CustomerController { + + public static final String BASE_URL = "/api/v1/customers"; + + + CustomerService customerService; + + @ApiOperation(value = "This will get a list of customers.", notes = "These are some notes about the API") + @GetMapping + @ResponseStatus(HttpStatus.OK) + public CustomerListDTO getAllCustomers (){ + + CustomerListDTO customerListDTO = new CustomerListDTO(); + customerListDTO.getCustomerDTOs().addAll( customerService.findAllCustomers()); + return customerListDTO; + } + + @GetMapping("/{id}") + @ResponseStatus(HttpStatus.OK) + public CustomerDTO getCustomerById(@PathVariable Long id){ + CustomerDTO customerDTO = customerService.findCustomerById(id); + customerDTO.setCustomerUrl(BASE_URL + id); + + + return customerDTO; + } + + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + // @RequestBody tell Sping mVC to look at the body of the request and parse it and try to create a + // CustomerDTO out of that + public CustomerDTO createNewCustomer(@RequestBody CustomerDTO customerDTO){ + return customerService.createNewCustomer(customerDTO); + } + + @PutMapping({"/{id}"}) + @ResponseStatus(HttpStatus.OK) + // @RequestBody tell Sping mVC to look at the body of the request and parse it and try to create a + // CustomerDTO out of that + public CustomerDTO updateCustomer( + @PathVariable Long id, + @RequestBody CustomerDTO customerDTO){ + return customerService.saveCustomerByDTO(id,customerDTO); + } + + @PatchMapping({"/{id}"}) + @ResponseStatus(HttpStatus.OK) + // @RequestBody tell Sping mVC to look at the body of the request and parse it and try to create a + // CustomerDTO out of that + public CustomerDTO patchCustomer( + @PathVariable Long id, + @RequestBody CustomerDTO customerDTO){ + return customerService.patchCustomer(id,customerDTO); + } + + + @DeleteMapping({"/{id}"}) + @ResponseStatus(HttpStatus.OK) + // @RequestBody tell Sping mVC to look at the body of the request and parse it and try to create a + // CustomerDTO out of that + public void deleteCustomer( + @PathVariable Long id){ + + customerService.deleteCustomerById(id); + + return ; + } +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring5-mvc-rest-app/src/main/java/guru/springfamework/controllers/v1/RestReponseEntityExceptionHandler.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/controllers/v1/RestReponseEntityExceptionHandler.java new file mode 100644 index 000000000..446751a25 --- /dev/null +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/controllers/v1/RestReponseEntityExceptionHandler.java @@ -0,0 +1,23 @@ +package guru.springfamework.controllers.v1; + +import guru.springfamework.services.ResourceNotFoundException; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +/** + * Darcy Xian 24/11/20 12:13 pm spring5-mvc-rest + */ +@ControllerAdvice +public class RestReponseEntityExceptionHandler extends ResponseEntityExceptionHandler { + + @ExceptionHandler({ResourceNotFoundException.class}) + public ResponseEntity handleNotFoundException(Exception exception, WebRequest request){ + + return new ResponseEntity("Resource not found",new HttpHeaders(), HttpStatus.NOT_FOUND); + } +} diff --git a/spring5-mvc-rest-app/src/main/java/guru/springfamework/controllers/v1/VendorController.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/controllers/v1/VendorController.java new file mode 100644 index 000000000..c0b9fa029 --- /dev/null +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/controllers/v1/VendorController.java @@ -0,0 +1,61 @@ +package guru.springfamework.controllers.v1; + +import guru.springfamework.services.VendorService; +import guru.springfamework.api.v1.model.VendorDTO; +import guru.springfamework.api.v1.model.VendorListDTO; +import io.swagger.annotations.Api; +import lombok.AllArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.*; + +/** + * Darcy Xian 24/11/20 4:23 pm spring5-mvc-rest + */ +@Api(description = "This is my Vendor controller") +@RestController +@RequestMapping(VendorController.BASE_URL) +@AllArgsConstructor +public class VendorController { + + VendorService vendorService; + public static final String BASE_URL = "/api/v1/vendors"; + @GetMapping + @ResponseStatus(HttpStatus.OK) + public VendorListDTO getAllVendors (){ + return new VendorListDTO(vendorService.findAllVendors()); + } + + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public VendorDTO createNewVendor(@RequestBody VendorDTO vendorDTO){ + return vendorService.createNewVendor(vendorDTO); + } + + @DeleteMapping("/{id}") + @ResponseStatus(HttpStatus.OK) + public void deleteById(@PathVariable Long id){ + vendorService.deleteById(id); + return ; + } + @GetMapping("/{id}") + @ResponseStatus(HttpStatus.OK) + public VendorDTO findById(@PathVariable Long id){ + VendorDTO vendorDTO = vendorService.findBYId(id); + vendorDTO.setVendorUrl(VendorController.BASE_URL + id); + return vendorDTO; + } + @PutMapping("/{id}") + @ResponseStatus(HttpStatus.OK) + public VendorDTO updateById( + @PathVariable Long id, + @RequestBody VendorDTO vendorDTO){ + return vendorService.saveById(id,vendorDTO); + } + @PatchMapping("/{id}") + @ResponseStatus(HttpStatus.OK) + public VendorDTO patchById(@PathVariable Long id, + @RequestBody VendorDTO vendorDTO){ + return vendorService.patchById(id,vendorDTO); + } + +} diff --git a/src/main/java/guru/springfamework/domain/Category.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/domain/Category.java similarity index 100% rename from src/main/java/guru/springfamework/domain/Category.java rename to spring5-mvc-rest-app/src/main/java/guru/springfamework/domain/Category.java diff --git a/spring5-mvc-rest-app/src/main/java/guru/springfamework/domain/Customer.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/domain/Customer.java new file mode 100644 index 000000000..4848a4299 --- /dev/null +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/domain/Customer.java @@ -0,0 +1,25 @@ + +package guru.springfamework.domain; + +import lombok.Data; +import org.springframework.context.annotation.Bean; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; +@Data +@Entity +public class Customer +{ + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + private String firstname; + private String lastname; + +} diff --git a/spring5-mvc-rest-app/src/main/java/guru/springfamework/domain/Vendor.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/domain/Vendor.java new file mode 100644 index 000000000..48542cf31 --- /dev/null +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/domain/Vendor.java @@ -0,0 +1,25 @@ + +package guru.springfamework.domain; + +import lombok.Data; +import org.hibernate.annotations.Generated; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; +@Data +@Entity +public class Vendor +{ + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + private String name; + private String nickName; + + +} diff --git a/src/main/java/guru/springfamework/repositories/CategoryRepository.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/repositories/CategoryRepository.java similarity index 86% rename from src/main/java/guru/springfamework/repositories/CategoryRepository.java rename to spring5-mvc-rest-app/src/main/java/guru/springfamework/repositories/CategoryRepository.java index 74dc77e17..e622f43f7 100644 --- a/src/main/java/guru/springfamework/repositories/CategoryRepository.java +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/repositories/CategoryRepository.java @@ -7,4 +7,6 @@ * Created by jt on 9/24/17. */ public interface CategoryRepository extends JpaRepository { + Category findByName(String name); + } diff --git a/spring5-mvc-rest-app/src/main/java/guru/springfamework/repositories/CustomerRepository.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/repositories/CustomerRepository.java new file mode 100644 index 000000000..13e9acc8b --- /dev/null +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/repositories/CustomerRepository.java @@ -0,0 +1,15 @@ +package guru.springfamework.repositories; + +import guru.springfamework.domain.Customer; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +/** + * Darcy Xian 22/11/20 5:16 pm spring5-mvc-rest + */ +@Repository +public interface CustomerRepository extends JpaRepository { + + + +} diff --git a/spring5-mvc-rest-app/src/main/java/guru/springfamework/repositories/VendorRepository.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/repositories/VendorRepository.java new file mode 100644 index 000000000..165434276 --- /dev/null +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/repositories/VendorRepository.java @@ -0,0 +1,13 @@ +package guru.springfamework.repositories; + +import guru.springfamework.domain.Vendor; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +/** + * Darcy Xian 24/11/20 3:57 pm spring5-mvc-rest + */ +@Repository +public interface VendorRepository extends JpaRepository { + +} diff --git a/spring5-mvc-rest-app/src/main/java/guru/springfamework/services/CategoryService.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/services/CategoryService.java new file mode 100644 index 000000000..27e73769e --- /dev/null +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/services/CategoryService.java @@ -0,0 +1,17 @@ +package guru.springfamework.services; + +import guru.springfamework.api.v1.model.CategoryDTO; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * Darcy Xian 21/11/20 6:40 pm spring5-mvc-rest + */ +@Service +public interface CategoryService { + + List getAllCategories (); + + CategoryDTO getCategoryByName(String name); +} diff --git a/spring5-mvc-rest-app/src/main/java/guru/springfamework/services/CategoryServiceImp.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/services/CategoryServiceImp.java new file mode 100644 index 000000000..be652ec69 --- /dev/null +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/services/CategoryServiceImp.java @@ -0,0 +1,37 @@ +package guru.springfamework.services; + +import guru.springfamework.api.v1.mapper.CategoryMapper; +import guru.springfamework.api.v1.model.CategoryDTO; +import guru.springfamework.repositories.CategoryRepository; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * Darcy Xian 21/11/20 6:48 pm spring5-mvc-rest + */ +@Service +public class CategoryServiceImp implements CategoryService { + + private final CategoryMapper categoryMapper; + private final CategoryRepository categoryRepository; + + public CategoryServiceImp(CategoryMapper categoryMapper, CategoryRepository categoryRepository) { + this.categoryMapper = categoryMapper; + this.categoryRepository = categoryRepository; + } + + @Override + public List getAllCategories() { + return categoryRepository.findAll() + .stream() + .map(categoryMapper::categoryToCategoryDTO) + .collect(Collectors.toList()); + } + + @Override + public CategoryDTO getCategoryByName(String name) { + return categoryMapper.categoryToCategoryDTO(categoryRepository.findByName(name)); + } +} diff --git a/spring5-mvc-rest-app/src/main/java/guru/springfamework/services/CustomerService.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/services/CustomerService.java new file mode 100644 index 000000000..048df0425 --- /dev/null +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/services/CustomerService.java @@ -0,0 +1,31 @@ +package guru.springfamework.services; + + + + + +import guru.springfamework.model.CustomerDTO; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * Darcy Xian 22/11/20 5:13 pm spring5-mvc-rest + */ + +@Service +public interface CustomerService { + + List findAllCustomers(); + + CustomerDTO findCustomerById(Long id); + + CustomerDTO createNewCustomer(CustomerDTO customerDTO); + + CustomerDTO saveCustomerByDTO(Long id, CustomerDTO customerDTO); + + CustomerDTO patchCustomer(Long id, CustomerDTO customerDTO); + + void deleteCustomerById(Long id); + +} diff --git a/spring5-mvc-rest-app/src/main/java/guru/springfamework/services/CustomerServiceImp.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/services/CustomerServiceImp.java new file mode 100644 index 000000000..3f619f46f --- /dev/null +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/services/CustomerServiceImp.java @@ -0,0 +1,152 @@ +package guru.springfamework.services; + +import guru.springfamework.controllers.v1.CustomerController; +import guru.springfamework.api.v1.mapper.CustomerMapper; + +import guru.springfamework.domain.Customer; +import guru.springfamework.model.CustomerDTO; +import guru.springfamework.repositories.CustomerRepository; + +import lombok.AllArgsConstructor; +import org.springframework.stereotype.Service; + + +import java.util.List; +import java.util.stream.Collectors; + +/** + * Darcy Xian 22/11/20 5:24 pm spring5-mvc-rest + */ + +@Service +@AllArgsConstructor +public class CustomerServiceImp implements CustomerService{ + + + + private final CustomerRepository customerRepository; + private final CustomerMapper customerMapper; + + @Override + public List findAllCustomers() { + + return customerRepository + .findAll() + .stream() + .map(customer -> { + CustomerDTO customerDTO = customerMapper.CustomerToCustomerDTO(customer); + customerDTO.setCustomerUrl( getCustomerUrl(customer.getId())); + return customerDTO; + }) + .collect(Collectors.toList()); + } + + @Override + public CustomerDTO findCustomerById(Long id) { + return customerRepository + .findById(id) + .map(customerMapper::CustomerToCustomerDTO) + .orElseThrow(ResourceNotFoundException::new); + } + + @Override + public CustomerDTO createNewCustomer(CustomerDTO customerDTO) { + + Customer customer = customerMapper.CustomerDTOToCustomer(customerDTO); + + Customer savedCustomer = customerRepository.save(customer); + + CustomerDTO returnDTO = customerMapper.CustomerToCustomerDTO(savedCustomer); + + returnDTO.setCustomerUrl(getCustomerUrl( savedCustomer.getId())); + + return returnDTO; + } + + @Override + public CustomerDTO saveCustomerByDTO(Long id, CustomerDTO customerDTO) { + customerDTO.setId(id); + + CustomerDTO customerDTO1 = customerMapper.CustomerToCustomerDTO( + customerRepository.save( + customerMapper.CustomerDTOToCustomer(customerDTO))); + + customerDTO1.setCustomerUrl(getCustomerUrl( id)); + return customerDTO1; + } + + @Override + public CustomerDTO patchCustomer(Long id, CustomerDTO customerDTO) { + return customerRepository.findById(id).map(customer ->{ + if(customerDTO.getFirstname() != null){ + customer.setFirstname(customerDTO.getFirstname()); + } + + if(customerDTO.getLastname() != null){ + customer.setLastname(customerDTO.getLastname()); + } + + + CustomerDTO customerDTO1 = customerMapper.CustomerToCustomerDTO(customerRepository.save(customer)); + customerDTO1.setCustomerUrl(getCustomerUrl(id)); + return customerDTO1; + }).orElseThrow(ResourceNotFoundException::new); + + } + @Override + public void deleteCustomerById(Long id){ + customerRepository.deleteById(id); + } + + private String getCustomerUrl(Long id){ + return CustomerController.BASE_URL + "/" + id; + } + + + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring5-mvc-rest-app/src/main/java/guru/springfamework/services/ResourceNotFoundException.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/services/ResourceNotFoundException.java new file mode 100644 index 000000000..25eded6b1 --- /dev/null +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/services/ResourceNotFoundException.java @@ -0,0 +1,22 @@ +package guru.springfamework.services; + +/** + * Darcy Xian 24/11/20 11:49 am spring5-mvc-rest + */ +public class ResourceNotFoundException extends RuntimeException { + + public ResourceNotFoundException(){ + + } + + public ResourceNotFoundException(String message){ + super(message); + } + + public ResourceNotFoundException(String message, Throwable cause){ + super(message, cause); + } + public ResourceNotFoundException (String message, Throwable cause, boolean enableSuppression, boolean writbleStackTrace){ + super(message,cause,enableSuppression,writbleStackTrace); + } +} diff --git a/spring5-mvc-rest-app/src/main/java/guru/springfamework/services/VendorService.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/services/VendorService.java new file mode 100644 index 000000000..c1fb5d253 --- /dev/null +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/services/VendorService.java @@ -0,0 +1,25 @@ +package guru.springfamework.services; + +import guru.springfamework.api.v1.model.VendorDTO; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * Darcy Xian 24/11/20 3:59 pm spring5-mvc-rest + */ +@Service +public interface VendorService { + + List findAllVendors(); + + VendorDTO createNewVendor(VendorDTO vendorDTO); + + void deleteById(Long id); + + VendorDTO findBYId(Long id); + + VendorDTO saveById(Long id, VendorDTO vendorDTO); + + VendorDTO patchById(Long id, VendorDTO vendorDTO); +} diff --git a/spring5-mvc-rest-app/src/main/java/guru/springfamework/services/VendorServiceImp.java b/spring5-mvc-rest-app/src/main/java/guru/springfamework/services/VendorServiceImp.java new file mode 100644 index 000000000..fe1fea6f9 --- /dev/null +++ b/spring5-mvc-rest-app/src/main/java/guru/springfamework/services/VendorServiceImp.java @@ -0,0 +1,111 @@ +package guru.springfamework.services; + +import guru.springfamework.controllers.v1.VendorController; +import guru.springfamework.api.v1.mapper.VendorMapper; +import guru.springfamework.api.v1.model.VendorDTO; +import guru.springfamework.domain.Vendor; +import guru.springfamework.repositories.VendorRepository; +import lombok.AllArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * Darcy Xian 24/11/20 4:04 pm spring5-mvc-rest + */ +@Service +@AllArgsConstructor +public class VendorServiceImp implements VendorService { + + VendorRepository vendorRepository; + VendorMapper vendorMapper; + + @Override + public List findAllVendors() { + return vendorRepository.findAll() + .stream() + .map(vendor -> { + VendorDTO vendorDTO = vendorMapper.vendorToVendorDTO(vendor); + vendorDTO.setVendorUrl(getVendorUrl(vendorDTO.getId())); + return vendorDTO; + }) + .collect(Collectors.toList()); + } + + @Override + public VendorDTO createNewVendor(VendorDTO vendorDTO) { + VendorDTO vendorDTO1 = vendorMapper.vendorToVendorDTO( vendorRepository.save(vendorMapper.vendorDTOToVendor + (vendorDTO))); + vendorDTO1.setVendorUrl(getVendorUrl(vendorDTO1.getId())); + return vendorDTO1; + + } + + @Override + public void deleteById(Long id) { + vendorRepository.deleteById(id); + return ; + } + + @Override + public VendorDTO findBYId(Long id) { + return vendorRepository.findById(id) + .map(vendorMapper::vendorToVendorDTO) + .orElseThrow(ResourceNotFoundException::new); + } + + @Override + public VendorDTO saveById(Long id, VendorDTO vendorDTO) { + vendorDTO.setId(id); + Vendor vendor = vendorMapper.vendorDTOToVendor(vendorDTO); + VendorDTO vendorDTO1 = vendorMapper.vendorToVendorDTO(vendorRepository.save(vendor)); + return vendorDTO1; + } + + @Override + public VendorDTO patchById(Long id, VendorDTO vendorDTO) { + return vendorRepository.findById(id) + .map(vendor -> { + if(vendorDTO.getName() != null){ + vendor.setName(vendorDTO.getName()); + } + if(vendorDTO.getNickName() != null){ + vendor.setNickName(vendorDTO.getNickName()); + } + vendorRepository.save(vendor); + VendorDTO vendorDTO1 = vendorMapper.vendorToVendorDTO(vendor); + vendorDTO1.setVendorUrl(getVendorUrl(id)); + return vendorDTO1; + }) + .orElseThrow(ResourceNotFoundException::new); + } + + public static String getVendorUrl(Long id){ + return VendorController.BASE_URL + "/"+ id; + } +} + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring5-mvc-rest-app/src/test/java/guru/springfamework/api/v1/mapper/CategoryMapperTest.java b/spring5-mvc-rest-app/src/test/java/guru/springfamework/api/v1/mapper/CategoryMapperTest.java new file mode 100644 index 000000000..221b9f477 --- /dev/null +++ b/spring5-mvc-rest-app/src/test/java/guru/springfamework/api/v1/mapper/CategoryMapperTest.java @@ -0,0 +1,34 @@ + +package guru.springfamework.api.v1.mapper; + +import guru.springfamework.api.v1.model.CategoryDTO; +import guru.springfamework.domain.Category; +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Darcy Xian 21/11/20 6:14 pm spring5-mvc-rest + */ +public class CategoryMapperTest { + + CategoryMapper categoryMapper = CategoryMapper.INSTANCE; + + @Test + public void categoryToCategoryDTO() throws Exception{ + + //given + Category category = new Category(); + category.setName("Joe"); + category.setId(1L); + + // when + CategoryDTO categoryDTO = categoryMapper.categoryToCategoryDTO(category); + + // then + assertEquals(Long.valueOf(1L), categoryDTO.getId()); + assertEquals("Joe", categoryDTO.getName()); + } + + +} \ No newline at end of file diff --git a/spring5-mvc-rest-app/src/test/java/guru/springfamework/api/v1/mapper/CustomerMapperTest.java b/spring5-mvc-rest-app/src/test/java/guru/springfamework/api/v1/mapper/CustomerMapperTest.java new file mode 100644 index 000000000..a0a4d370a --- /dev/null +++ b/spring5-mvc-rest-app/src/test/java/guru/springfamework/api/v1/mapper/CustomerMapperTest.java @@ -0,0 +1,39 @@ +package guru.springfamework.api.v1.mapper; + + +import guru.springfamework.domain.Customer; +import guru.springfamework.model.CustomerDTO; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Darcy Xian 22/11/20 6:33 pm spring5-mvc-rest + */ +public class CustomerMapperTest { + + private static final String FIRSTNAME = "Joe"; + private static final String LASTNAME = "Lin"; + + CustomerMapper customerMapper = CustomerMapper.INSTANCE; + + @Test + public void customerToCustomerDTO() { + // given + Customer customer = new Customer(); + customer.setFirstname(FIRSTNAME); + customer.setLastname(LASTNAME); + customer.setId(1L); + + // when + CustomerDTO customerDTO1 = customerMapper.CustomerToCustomerDTO(customer); + + // then + assertEquals(Long.valueOf(1L), customerDTO1.getId()); + assertEquals(FIRSTNAME,customerDTO1.getFirstname()); + assertEquals(LASTNAME,customerDTO1.getLastname()); + + + } +} \ No newline at end of file diff --git a/spring5-mvc-rest-app/src/test/java/guru/springfamework/api/v1/mapper/VendorMapperTest.java b/spring5-mvc-rest-app/src/test/java/guru/springfamework/api/v1/mapper/VendorMapperTest.java new file mode 100644 index 000000000..387319d9b --- /dev/null +++ b/spring5-mvc-rest-app/src/test/java/guru/springfamework/api/v1/mapper/VendorMapperTest.java @@ -0,0 +1,57 @@ + +package guru.springfamework.api.v1.mapper; + +import guru.springfamework.api.v1.model.VendorDTO; +import guru.springfamework.domain.Vendor; +import org.junit.Before; +import org.junit.Test; + +import java.util.NavigableMap; + +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +/** + * Darcy Xian 24/11/20 3:42 pm spring5-mvc-rest + */ +public class VendorMapperTest { + + private static final String NAME = "JJJ"; + private static final String URL = "kkkk"; + VendorMapper vendorMapper = VendorMapper.INSTANCE; + + @Test + public void vendorToVendorDTO() { + //given + Vendor vendor = new Vendor(); + vendor.setId(1L); + vendor.setName(NAME); + + + // when + VendorDTO vendorDTO = vendorMapper.vendorToVendorDTO(vendor); + + // then + assertEquals(Long.valueOf(1L),vendorDTO.getId()); + assertEquals(NAME,vendorDTO.getName()); + + } + + @Test + public void vendorDTOToVendor() { + //given + VendorDTO vendorDTO = new VendorDTO(); + vendorDTO.setId(1L); + vendorDTO.setName(NAME); + + + // when + Vendor vendor1 = vendorMapper.vendorDTOToVendor(vendorDTO); + + // then + assertEquals(Long.valueOf(1L),vendor1.getId()); + assertEquals(NAME,vendor1.getName()); + } + +} \ No newline at end of file diff --git a/spring5-mvc-rest-app/src/test/java/guru/springfamework/controllers/v1/AbstractControllerTest.java b/spring5-mvc-rest-app/src/test/java/guru/springfamework/controllers/v1/AbstractControllerTest.java new file mode 100644 index 000000000..64517b513 --- /dev/null +++ b/spring5-mvc-rest-app/src/test/java/guru/springfamework/controllers/v1/AbstractControllerTest.java @@ -0,0 +1,17 @@ +package guru.springfamework.controllers.v1; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * Darcy Xian 22/11/20 9:07 pm spring5-mvc-rest + */ +public abstract class AbstractControllerTest { + + public static String asJsonString(final Object ob){ + try{ + return new ObjectMapper().writeValueAsString(ob); + } catch (Exception e){ + throw new RuntimeException(e); + } + } +} \ No newline at end of file diff --git a/spring5-mvc-rest-app/src/test/java/guru/springfamework/controllers/v1/CategoryControllerTest.java b/spring5-mvc-rest-app/src/test/java/guru/springfamework/controllers/v1/CategoryControllerTest.java new file mode 100644 index 000000000..1ef82ea49 --- /dev/null +++ b/spring5-mvc-rest-app/src/test/java/guru/springfamework/controllers/v1/CategoryControllerTest.java @@ -0,0 +1,101 @@ + +package guru.springfamework.controllers.v1; + +import guru.springfamework.api.v1.model.CategoryDTO; +import guru.springfamework.services.CategoryService; +import guru.springfamework.services.ResourceNotFoundException; +import lombok.extern.slf4j.Slf4j; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.util.Arrays; +import java.util.List; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +/** + * Darcy Xian 22/11/20 11:24 am spring5-mvc-rest + */ +@Slf4j +public class CategoryControllerTest { + + public static final String NAME = "Joe"; + + @Mock + CategoryService categoryService; + + @InjectMocks + CategoryController categoryController; + + MockMvc mockMvc; + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + + mockMvc = MockMvcBuilders.standaloneSetup(categoryController) + .setControllerAdvice(new RestReponseEntityExceptionHandler()).build(); + } + + @Test + public void testGetAllCategories() throws Exception { + //given + CategoryDTO categoryDTO = new CategoryDTO(); + categoryDTO.setId(1L); + categoryDTO.setName(NAME); + + CategoryDTO categoryDTO1 = new CategoryDTO(); + categoryDTO1.setName("Bob"); + categoryDTO1.setId(2L); + + List c = Arrays.asList(categoryDTO,categoryDTO1); + + when(categoryService.getAllCategories()).thenReturn(c); + + + // when + mockMvc.perform(get("/api/v1/categories/") + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + // categoryListDTOS 是 CategoryListDTO 里的 property + .andExpect(jsonPath("$.categoryListDTOS", hasSize(2))); + + + } + + @Test + public void getCategoryByName() throws Exception { + + CategoryDTO categoryDTO = new CategoryDTO(); + categoryDTO.setId(1L); + categoryDTO.setName(NAME); + + when(categoryService.getCategoryByName(anyString())).thenReturn(categoryDTO); + + mockMvc.perform(get("/api/v1/categories/Joe") + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.name",equalTo(NAME))); + } + @Test + public void testGetByNameNotFound() throws Exception{ + when(categoryService.getCategoryByName(anyString())).thenThrow(ResourceNotFoundException.class); + + mockMvc.perform(get(CategoryController.BASE_URL + "/Foo") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isNotFound()); + + } +} diff --git a/spring5-mvc-rest-app/src/test/java/guru/springfamework/controllers/v1/CustomerControllerTest.java b/spring5-mvc-rest-app/src/test/java/guru/springfamework/controllers/v1/CustomerControllerTest.java new file mode 100644 index 000000000..df5920ffc --- /dev/null +++ b/spring5-mvc-rest-app/src/test/java/guru/springfamework/controllers/v1/CustomerControllerTest.java @@ -0,0 +1,168 @@ +package guru.springfamework.controllers.v1; + + +import guru.springfamework.model.CustomerDTO; +import guru.springfamework.services.CustomerService; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import static guru.springfamework.controllers.v1.AbstractControllerTest.asJsonString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; + +import java.util.Arrays; +import java.util.List; + + +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +/** + * Darcy Xian 22/11/20 5:51 pm spring5-mvc-rest + */ + +public class CustomerControllerTest { + + public static final String FIRSTNAME = "JOE"; + public static final String LASTNAME = "LING"; + + @Mock + CustomerService customerService; + + @InjectMocks + CustomerController customerController; + + MockMvc mockMvc; + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + mockMvc = MockMvcBuilders.standaloneSetup(customerController) + .setControllerAdvice(new RestReponseEntityExceptionHandler()) + .build(); + } + + @Test + public void getAllCustomers() throws Exception { + // given + + List customerDTOS = Arrays.asList(new CustomerDTO(),new CustomerDTO(), new CustomerDTO()); + when(customerService.findAllCustomers()).thenReturn(customerDTOS); + + // then + mockMvc.perform(get("/api/v1/customers/") + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.customerDTOs", hasSize(3))); + } + + @Test + public void getCustomerById() throws Exception { + + // given + CustomerDTO customerDTO = new CustomerDTO(); + customerDTO.setFirstname(FIRSTNAME); + customerDTO.setLastname(LASTNAME); + customerDTO.setId(1L); + + when(customerService.findCustomerById(1L)).thenReturn(customerDTO); + + mockMvc.perform(get("/api/v1/customers/1") + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.firstname", equalTo(FIRSTNAME))); + } +// @Test +// public void createNewCustomer() throws Exception { +// // given +// CustomerDTO customerDTO = new CustomerDTO(); +// customerDTO.setFirstname(FIRSTNAME); +// customerDTO.setLastname(LASTNAME); +// +// CustomerDTO returnDTO = new CustomerDTO(); +// returnDTO.setFirstname(customerDTO.getFirstname()); +// returnDTO.setLastname(customerDTO.getLastname()); +// returnDTO.setCustomerUrl("/api/v1/customers/1"); +// +// when(customerService.createNewCustomer(customerDTO)).thenReturn(returnDTO); +// +// mockMvc.perform(post("/api/v1/customers/") +// .contentType(MediaType.APPLICATION_JSON) +// // 把一个对象转化成json 利用jackson的jar包 +// .contentType(asJsonString(customerDTO))) +// .andExpect(status().isOk()) +// .andExpect(jsonPath("$.firstname",equalTo("Fred"))); +// // .andExpect(jsonPath("$.customer_url",equalTo("/api/v1/customers/1"))); +// +// } + + @Test + public void testUpdateCustomer() throws Exception{ + CustomerDTO customerDTO = new CustomerDTO(); + customerDTO.setFirstname(FIRSTNAME); + customerDTO.setLastname(LASTNAME); + + CustomerDTO returnDTO = new CustomerDTO(); + returnDTO.setId(1l); + returnDTO.setFirstname(customerDTO.getFirstname()); + returnDTO.setLastname(customerDTO.getLastname()); + returnDTO.setCustomerUrl("/api/v1/customers/1"); + + when(customerService.saveCustomerByDTO(anyLong(),any(CustomerDTO.class))).thenReturn(returnDTO); + + // when then + mockMvc.perform(put("/api/v1/customers/1") + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(customerDTO))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.firstname",equalTo(FIRSTNAME))); + } + @Test + public void testPatchCustomer() throws Exception{ + //given + CustomerDTO customerDTO = new CustomerDTO(); + customerDTO.setFirstname(FIRSTNAME); + + CustomerDTO returnDTO = new CustomerDTO(); + returnDTO.setFirstname(customerDTO.getFirstname()); + returnDTO.setLastname("bobb"); + returnDTO.setCustomerUrl("/api/v1/customers/1"); + + when(customerService.patchCustomer(anyLong(),any(CustomerDTO.class))).thenReturn(returnDTO); + + // when then + mockMvc.perform(patch(CustomerController.BASE_URL + "/1") + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(customerDTO))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.firstname",equalTo(FIRSTNAME))) + .andExpect(jsonPath("$.lastname",equalTo("bobb"))) + .andExpect(jsonPath("$.customerUrl",equalTo("/api/v1/customers/1"))); + } + + @Test + public void testDeleteCUstomer() throws Exception{ + mockMvc.perform(delete("/api/v1/customers/1") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + + verify(customerService).deleteCustomerById(anyLong()); + } + + +} \ No newline at end of file diff --git a/spring5-mvc-rest-app/src/test/java/guru/springfamework/controllers/v1/VendorControllerTest.java b/spring5-mvc-rest-app/src/test/java/guru/springfamework/controllers/v1/VendorControllerTest.java new file mode 100644 index 000000000..b9c8659ab --- /dev/null +++ b/spring5-mvc-rest-app/src/test/java/guru/springfamework/controllers/v1/VendorControllerTest.java @@ -0,0 +1,148 @@ +package guru.springfamework.controllers.v1; + + +import guru.springfamework.api.v1.model.VendorDTO; +import guru.springfamework.services.VendorService; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import java.util.Arrays; +import java.util.List; + +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** + * Darcy Xian 24/11/20 4:34 pm spring5-mvc-rest + */ +@RunWith(SpringRunner.class) +@WebMvcTest(controllers = {VendorController.class}) +// which bring up a small segment of the Spring Context and just for the web Front-end. +public class VendorControllerTest extends AbstractControllerTest { + + private static final String NAME = "kkkk"; + private static final String NICKNAME = "bbbb"; + @MockBean // provided by Spring Context no need to init anymore + VendorService vendorService; + + @Autowired // 和上面相呼应 vendorController.class 会被 autowired + MockMvc mockMvc; + + @Before + public void setUp() throws Exception { + + } + + @Test + public void getAllVendors() throws Exception { + // given + List vendorDTOss = Arrays.asList(new VendorDTO(),new VendorDTO(),new VendorDTO()); + + when(vendorService.findAllVendors()).thenReturn(vendorDTOss); + + // when then + mockMvc.perform(get(VendorController.BASE_URL) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.vendorDTOS",hasSize(3))); + + } + @Test + public void createNewVendor() throws Exception { + //given + VendorDTO vendorDTO = new VendorDTO(); + vendorDTO.setName(NAME); + vendorDTO.setNickName(NICKNAME); + + when(vendorService.createNewVendor(any(VendorDTO.class))).thenReturn(vendorDTO); + + + //when then + mockMvc.perform(post(VendorController.BASE_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(vendorDTO))) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.name",equalTo(NAME))) + .andExpect(jsonPath("$.nickName",equalTo(NICKNAME))); + } + @Test + public void deleteById() throws Exception{ + mockMvc.perform(delete(VendorController.BASE_URL+"/" + anyLong()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + verify(vendorService).deleteById(anyLong()); + } + @Test + public void findById() throws Exception{ + //given + VendorDTO vendorDTO = new VendorDTO(); + vendorDTO.setName(NAME); + vendorDTO.setNickName(NICKNAME); + + when(vendorService.findBYId(anyLong())).thenReturn(vendorDTO); + + // when then + mockMvc.perform(get(VendorController.BASE_URL+"/"+anyLong()) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(vendorDTO))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.name",equalTo(NAME))) + .andExpect(jsonPath("$.nickName",equalTo(NICKNAME))); + } + @Test + public void upDateById() throws Exception{ + //given + VendorDTO vendorDTO = new VendorDTO(); + vendorDTO.setId(1L); + vendorDTO.setName(NAME); + vendorDTO.setNickName(NICKNAME); + + when(vendorService.saveById(anyLong(),any(VendorDTO.class))).thenReturn(vendorDTO); + // when then + mockMvc.perform(put(VendorController.BASE_URL+"/"+ 1) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(vendorDTO))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.name",equalTo(NAME))) + .andExpect(jsonPath("$.nickName",equalTo(NICKNAME))); + } + @Test + public void patchById() throws Exception{ + // given + VendorDTO vendorDTO = new VendorDTO(); + vendorDTO.setId(1L); + vendorDTO.setName(NAME); + vendorDTO.setNickName(NICKNAME); + + when(vendorService.patchById(anyLong(),any(VendorDTO.class))).thenReturn(vendorDTO); + + // when then + mockMvc.perform(patch(VendorController.BASE_URL+ "/" + 1) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(vendorDTO))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.name",equalTo(vendorDTO.getName()))) + .andExpect(jsonPath("$.nickName",equalTo(vendorDTO.getNickName()))); + + + + } + + +} \ No newline at end of file diff --git a/spring5-mvc-rest-app/src/test/java/guru/springfamework/services/CategoryServiceImpTest.java b/spring5-mvc-rest-app/src/test/java/guru/springfamework/services/CategoryServiceImpTest.java new file mode 100644 index 000000000..8e5709d38 --- /dev/null +++ b/spring5-mvc-rest-app/src/test/java/guru/springfamework/services/CategoryServiceImpTest.java @@ -0,0 +1,10 @@ +package guru.springfamework.services; + +import static org.junit.Assert.*; + +/** + * Darcy Xian 1/12/20 10:53 pm spring5-mvc-rest + */ +public class CategoryServiceImpTest { + +} \ No newline at end of file diff --git a/spring5-mvc-rest-app/src/test/java/guru/springfamework/services/CategoryServiceTest.java b/spring5-mvc-rest-app/src/test/java/guru/springfamework/services/CategoryServiceTest.java new file mode 100644 index 000000000..608355e7f --- /dev/null +++ b/spring5-mvc-rest-app/src/test/java/guru/springfamework/services/CategoryServiceTest.java @@ -0,0 +1,75 @@ + +package guru.springfamework.services; + +import guru.springfamework.api.v1.mapper.CategoryMapper; +import guru.springfamework.api.v1.model.CategoryDTO; +import guru.springfamework.domain.Category; +import guru.springfamework.repositories.CategoryRepository; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.lang.reflect.Array; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.when; + +/** + * Darcy Xian 21/11/20 7:02 pm spring5-mvc-rest + */ +public class CategoryServiceTest { + + public static final Long ID = 2L; + public static final String NAME = "Jimmy"; + CategoryService categoryService; + @Mock + CategoryRepository categoryRepository; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + + categoryService = new CategoryServiceImp(CategoryMapper.INSTANCE,categoryRepository); + } + + @Test + public void getAllCategories() { + + // given + List categories = Arrays.asList(new Category(), new Category(), new Category()); + + when(categoryRepository.findAll()).thenReturn(categories); + + // when + List categoryDTOS = categoryService.getAllCategories(); + + // then + assertEquals(3,categoryDTOS.size()); + + + } + + @Test + public void getCategoryByName() { + + // given + Category category = new Category(); + category.setName(NAME); + category.setId(ID); + + when(categoryRepository.findByName(NAME)).thenReturn(category); + + // when + CategoryDTO category1 = categoryService.getCategoryByName(NAME); + + // then + assertEquals(NAME,category1.getName()); + assertEquals(ID,category1.getId()); + + + + } +} \ No newline at end of file diff --git a/spring5-mvc-rest-app/src/test/java/guru/springfamework/services/CustomerServiceImpIT.java b/spring5-mvc-rest-app/src/test/java/guru/springfamework/services/CustomerServiceImpIT.java new file mode 100644 index 000000000..23110039d --- /dev/null +++ b/spring5-mvc-rest-app/src/test/java/guru/springfamework/services/CustomerServiceImpIT.java @@ -0,0 +1,115 @@ + +package guru.springfamework.services; + +import guru.springfamework.api.v1.mapper.CustomerMapper; + +import guru.springfamework.bootstrap.Bootstrap; +import guru.springfamework.domain.Customer; +import guru.springfamework.model.CustomerDTO; +import guru.springfamework.repositories.CategoryRepository; +import guru.springfamework.repositories.CustomerRepository; + +import guru.springfamework.repositories.VendorRepository; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; + +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.List; + + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.*; + + +/** + * Darcy Xian 23/11/20 10:35 am spring5-mvc-rest + */ +@RunWith(SpringRunner.class) +@DataJpaTest // It brings up a smaller set of the Spring Boot Context,where it essentially sets up the data layer. +public class CustomerServiceImpIT { + + @Autowired + CustomerRepository customerRepository; + @Autowired + CategoryRepository categoryRepository; + @Autowired + VendorRepository vendorRepository; + + CustomerService customerService; + + @Before + public void setUp() throws Exception { + System.out.println("Loading Customer Data"); + System.out.println(customerRepository.findAll().size()); + + //setup data for testing + Bootstrap bootstrap = new Bootstrap(categoryRepository,customerRepository,vendorRepository); + bootstrap.run(); // loade data + + customerService = new CustomerServiceImp(customerRepository, CustomerMapper.INSTANCE); + } + @Test + public void patchCustomerUpdateFirstName() throws Exception{ + String updateName = "UpdateName"; + Long id = getCustomerIdValue(); + + Customer originalCustomer = customerRepository.getOne(id); + assertNotNull(originalCustomer); + //save original first name + String originalFirstName = originalCustomer.getFirstname(); + String originalLastName = originalCustomer.getLastname(); + + CustomerDTO customerDTO = new CustomerDTO(); + customerDTO.setFirstname(updateName); + + customerService.patchCustomer(id,customerDTO); + + Customer updatedCustomer = customerRepository.findById(id).get(); + + assertNotNull(updatedCustomer); + + assertNotEquals(originalFirstName,updatedCustomer.getFirstname()); + assertEquals(originalLastName,updatedCustomer.getLastname()); + + } + @Test + public void patchCustomerUpdateLastName() throws Exception{ + String updateName = "UpdateName"; + Long id = getCustomerIdValue(); + + Customer originalCustomer = customerRepository.getOne(id); + assertNotNull(originalCustomer); + //save original first name + String originalFirstName = originalCustomer.getFirstname(); + String originalLastName = originalCustomer.getLastname(); + + CustomerDTO customerDTO = new CustomerDTO(); + customerDTO.setLastname(updateName); + + customerService.patchCustomer(id,customerDTO); + + // 从新找出修改后的记录 + Customer updatedCustomer = customerRepository.findById(id).get(); + + assertNotNull(updatedCustomer); + + assertEquals(originalFirstName,updatedCustomer.getFirstname()); + assertNotEquals(originalLastName,updatedCustomer.getLastname()); + } + + private Long getCustomerIdValue(){ + List customers = customerRepository.findAll(); + System.out.println("Customers Found:" + customers.size()); + + // return first id + return customers.get(0).getId(); + + } + + +} + diff --git a/spring5-mvc-rest-app/src/test/java/guru/springfamework/services/CustomerServiceTest.java b/spring5-mvc-rest-app/src/test/java/guru/springfamework/services/CustomerServiceTest.java new file mode 100644 index 000000000..7bf732c86 --- /dev/null +++ b/spring5-mvc-rest-app/src/test/java/guru/springfamework/services/CustomerServiceTest.java @@ -0,0 +1,116 @@ + +package guru.springfamework.services; + +import guru.springfamework.api.v1.mapper.CustomerMapper; + +import guru.springfamework.domain.Customer; +import guru.springfamework.model.CustomerDTO; +import guru.springfamework.repositories.CustomerRepository; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +/** + * Darcy Xian 22/11/20 6:41 pm spring5-mvc-rest + */ +public class CustomerServiceTest { + + private static final Long ID = 2L; + + CustomerService customerService; + + @Mock + CustomerRepository customerRepository; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + customerService = new CustomerServiceImp(customerRepository, CustomerMapper.INSTANCE); + } + + @Test + public void findAllCustomers() { + //given + List customers = Arrays.asList(new Customer(),new Customer(),new Customer()); + + when(customerRepository.findAll()).thenReturn(customers); + //when + List customerDTOS = customerService.findAllCustomers(); + + // then + assertEquals(3,customerDTOS.size()); + } + + @Test + public void findCustomerById() { + // given + Customer customer = new Customer(); + customer.setId(1L); + + when(customerRepository.findById(1L)).thenReturn(java.util.Optional.of(customer)); + + //when + CustomerDTO customerDTO = customerService.findCustomerById(1L); + + // then + assertEquals(Long.valueOf(1L),customerDTO.getId()); + } + + @Test + public void createNewCustomer() throws Exception{ + // given + CustomerDTO customerDTO = new CustomerDTO(); + customerDTO.setFirstname("lim"); + + Customer savedCustomer = new Customer(); + savedCustomer.setId(1L); + savedCustomer.setFirstname(customerDTO.getFirstname()); + + when(customerRepository.save(any((Customer.class)))).thenReturn(savedCustomer); + + // when + CustomerDTO savedDto = customerService.createNewCustomer(customerDTO); + + //then + assertEquals(customerDTO.getFirstname(), savedDto.getFirstname()); + // assertEquals("/api/v1/customer/1", savedDto.getCustomerUrl()); + } + + @Test + public void saveCustomerByDTO() throws Exception{ + // given + CustomerDTO customerDTO = new CustomerDTO(); + customerDTO.setFirstname("lim"); + + Customer savedCustomer = new Customer(); + savedCustomer.setId(1L); + savedCustomer.setFirstname(customerDTO.getFirstname()); + + when(customerRepository.save(any((Customer.class)))).thenReturn(savedCustomer); + + // when + CustomerDTO savedDto = customerService.saveCustomerByDTO(1L,customerDTO); + + //then + assertEquals(customerDTO.getFirstname(), savedDto.getFirstname()); +// assertEquals("/api/v1/customer/1", savedDto.getCustomerUrl()); + } + + @Test + public void testDeleteCustomerById() throws Exception{ + Long id = 1L; + + customerRepository.deleteById(id); + + verify(customerRepository, times(1)).deleteById(anyLong()); + + } +} diff --git a/spring5-mvc-rest-app/src/test/java/guru/springfamework/services/VendorServiceTest.java b/spring5-mvc-rest-app/src/test/java/guru/springfamework/services/VendorServiceTest.java new file mode 100644 index 000000000..24bc8d90b --- /dev/null +++ b/spring5-mvc-rest-app/src/test/java/guru/springfamework/services/VendorServiceTest.java @@ -0,0 +1,125 @@ +package guru.springfamework.services; + +import guru.springfamework.api.v1.mapper.VendorMapper; +import guru.springfamework.api.v1.model.VendorDTO; +import guru.springfamework.domain.Vendor; +import guru.springfamework.repositories.VendorRepository; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.then; +/** + * Darcy Xian 24/11/20 4:15 pm spring5-mvc-rest + */ +public class VendorServiceTest { + + VendorService vendorService; + @Mock + VendorRepository vendorRepository; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + vendorService = new VendorServiceImp(vendorRepository, VendorMapper.INSTANCE); + } + + @Test + public void findAllVendors() { + //given + List vendors = Arrays.asList(new Vendor(),new Vendor(),new Vendor()); + + when(vendorRepository.findAll()).thenReturn(vendors); + // when + List vendorDTOS = vendorService.findAllVendors(); + // then + assertEquals(3,vendorDTOS.size()); + } + @Test + public void createNewVendors(){ + //given + Vendor vendor = new Vendor(); + vendor.setName("Bobb"); + + given(vendorRepository.save(any(Vendor.class))).willReturn(vendor); + // when + VendorDTO vendorDTO = vendorService.createNewVendor(new VendorDTO()); + + // then + assertEquals("Bobb",vendorDTO.getName()); + + + } + @Test + public void deleteById(){ + Long id = 1L; + + vendorRepository.deleteById(id); + + verify(vendorRepository,times(1)).deleteById(anyLong()); + then(vendorRepository).should().deleteById(anyLong()); + } + + @Test + public void findByid() throws Exception { + //given + Vendor vendor = new Vendor(); + vendor.setId(1L); + vendor.setName("Bobb"); + + when(vendorRepository.findById(anyLong())).thenReturn(java.util.Optional.of(vendor)); + // when + VendorDTO vendorDTO = vendorService.findBYId(1L); + // then + assertEquals("Bobb",vendorDTO.getName()); + } + @Test + public void saveById() throws Exception{ + //given 输入的DTO + VendorDTO vendorDTO = new VendorDTO(); + vendorDTO.setName("bobb"); + vendorDTO.setNickName("aoaa"); + + Vendor savedVendor = new Vendor(); + savedVendor.setName(vendorDTO.getName()); + savedVendor.setNickName(vendorDTO.getNickName()); + + when(vendorRepository.save(any(Vendor.class))).thenReturn(savedVendor); + //when + VendorDTO vendorDTO1 = vendorService.saveById(1L,vendorDTO); + //then + + assertEquals("bobb",vendorDTO1.getName()); + assertEquals("aoaa",vendorDTO1.getNickName()); + } + @Test + public void patchById(){ + // given + Vendor vendor = new Vendor(); + vendor.setId(1L); + vendor.setNickName("aaa"); + vendor.setName("aaa"); + + VendorDTO vendorDTO = new VendorDTO(); + + when(vendorRepository.findById(anyLong())).thenReturn(java.util.Optional.of(vendor)); + when(vendorRepository.save(any(Vendor.class))).thenReturn(vendor); + + // when + VendorDTO vendorDTO1 = vendorService.patchById(anyLong(),vendorDTO); + // then + // 'should' defaults to times = 1 + verify(vendorRepository,times(1)).findById(anyLong()); + verify(vendorRepository,times(1)).save(any(Vendor.class)); + + } + +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/test/java/guru/springfamework/spring5mvcrest/Spring5MvcRestApplicationTests.java b/src/test/java/guru/springfamework/spring5mvcrest/Spring5MvcRestApplicationTests.java deleted file mode 100644 index 6700ee154..000000000 --- a/src/test/java/guru/springfamework/spring5mvcrest/Spring5MvcRestApplicationTests.java +++ /dev/null @@ -1,16 +0,0 @@ -package guru.springfamework.spring5mvcrest; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class Spring5MvcRestApplicationTests { - - @Test - public void contextLoads() { - } - -}