Eric Goebelbecker
2018-05-30 22:34:01 -04:00
committed by maibin
parent 8e36e2b155
commit 6e94f0343c
75 changed files with 965 additions and 50 deletions
@@ -0,0 +1,31 @@
package com.baeldung.graphql;
public class Author {
private String id;
private String name;
private String thumbnail;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
}
@@ -0,0 +1,16 @@
package com.baeldung.graphql;
import java.util.List;
import java.util.Optional;
public class AuthorDao {
private List<Author> authors;
public AuthorDao(List<Author> authors) {
this.authors = authors;
}
public Optional<Author> getAuthor(String id) {
return authors.stream().filter(author -> id.equals(author.getId())).findFirst();
}
}
@@ -0,0 +1,17 @@
package com.baeldung.graphql;
import java.util.List;
import com.coxautodev.graphql.tools.GraphQLResolver;
public class AuthorResolver implements GraphQLResolver<Author> {
private PostDao postDao;
public AuthorResolver(PostDao postDao) {
this.postDao = postDao;
}
public List<Post> getPosts(Author author) {
return postDao.getAuthorPosts(author.getId());
}
}
@@ -0,0 +1,59 @@
package com.baeldung.graphql;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class GraphqlConfiguration {
@Bean
public PostDao postDao() {
List<Post> posts = new ArrayList<>();
for (int postId = 0; postId < 10; ++postId) {
for (int authorId = 0; authorId < 10; ++authorId) {
Post post = new Post();
post.setId("Post" + authorId + postId);
post.setTitle("Post " + authorId + ":" + postId);
post.setText("Post " + postId + " + by author " + authorId);
post.setAuthorId("Author" + authorId);
posts.add(post);
}
}
return new PostDao(posts);
}
@Bean
public AuthorDao authorDao() {
List<Author> authors = new ArrayList<>();
for (int authorId = 0; authorId < 10; ++authorId) {
Author author = new Author();
author.setId("Author" + authorId);
author.setName("Author " + authorId);
author.setThumbnail("http://example.com/authors/" + authorId);
authors.add(author);
}
return new AuthorDao(authors);
}
@Bean
public PostResolver postResolver(AuthorDao authorDao) {
return new PostResolver(authorDao);
}
@Bean
public AuthorResolver authorResolver(PostDao postDao) {
return new AuthorResolver(postDao);
}
@Bean
public Query query(PostDao postDao) {
return new Query(postDao);
}
@Bean
public Mutation mutation(PostDao postDao) {
return new Mutation(postDao);
}
}
@@ -0,0 +1,25 @@
package com.baeldung.graphql;
import java.util.UUID;
import com.coxautodev.graphql.tools.GraphQLMutationResolver;
public class Mutation implements GraphQLMutationResolver {
private PostDao postDao;
public Mutation(PostDao postDao) {
this.postDao = postDao;
}
public Post writePost(String title, String text, String category, String author) {
Post post = new Post();
post.setId(UUID.randomUUID().toString());
post.setTitle(title);
post.setText(text);
post.setCategory(category);
post.setAuthorId(author);
postDao.savePost(post);
return post;
}
}
@@ -0,0 +1,49 @@
package com.baeldung.graphql;
public class Post {
private String id;
private String title;
private String text;
private String category;
private String authorId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getAuthorId() {
return authorId;
}
public void setAuthorId(String authorId) {
this.authorId = authorId;
}
}
@@ -0,0 +1,24 @@
package com.baeldung.graphql;
import java.util.List;
import java.util.stream.Collectors;
public class PostDao {
private List<Post> posts;
public PostDao(List<Post> posts) {
this.posts = posts;
}
public List<Post> getRecentPosts(int count, int offset) {
return posts.stream().skip(offset).limit(count).collect(Collectors.toList());
}
public List<Post> getAuthorPosts(String author) {
return posts.stream().filter(post -> author.equals(post.getAuthorId())).collect(Collectors.toList());
}
public void savePost(Post post) {
posts.add(0, post);
}
}
@@ -0,0 +1,17 @@
package com.baeldung.graphql;
import java.util.Optional;
import com.coxautodev.graphql.tools.GraphQLResolver;
public class PostResolver implements GraphQLResolver<Post> {
private AuthorDao authorDao;
public PostResolver(AuthorDao authorDao) {
this.authorDao = authorDao;
}
public Optional<Author> getAuthor(Post post) {
return authorDao.getAuthor(post.getAuthorId());
}
}
@@ -0,0 +1,17 @@
package com.baeldung.graphql;
import java.util.List;
import com.coxautodev.graphql.tools.GraphQLQueryResolver;
public class Query implements GraphQLQueryResolver {
private PostDao postDao;
public Query(PostDao postDao) {
this.postDao = postDao;
}
public List<Post> recentPosts(int count, int offset) {
return postDao.getRecentPosts(count, offset);
}
}
@@ -0,0 +1,50 @@
package com.baeldung.shutdown;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.ApplicationPidFileWriter;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
// closeApplication();
// exitApplication();
// writePID();
}
private static void closeApplication() {
ConfigurableApplicationContext ctx = new SpringApplicationBuilder(Application.class).web(WebApplicationType.NONE).run();
System.out.println("Spring Boot application started");
ctx.getBean(TerminateBean.class);
ctx.close();
}
private static void exitApplication() {
ConfigurableApplicationContext ctx = new SpringApplicationBuilder(Application.class).web(WebApplicationType.NONE).run();
int exitCode = SpringApplication.exit(ctx, () -> {
// return the error code
return 0;
});
System.out.println("Exit Spring Boot");
System.exit(exitCode);
}
private static void writePID() {
SpringApplicationBuilder app = new SpringApplicationBuilder(Application.class).web(WebApplicationType.NONE);
app.build().addListeners(new ApplicationPidFileWriter("./bin/shutdown.pid"));
app.run();
}
}
@@ -0,0 +1,15 @@
package com.baeldung.shutdown;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.baeldung.shutdown")
public class ShutdownConfig {
@Bean
public TerminateBean getTerminateBean() {
return new TerminateBean();
}
}
@@ -0,0 +1,11 @@
package com.baeldung.shutdown;
import javax.annotation.PreDestroy;
public class TerminateBean {
@PreDestroy
public void onDestroy() throws Exception {
System.out.println("Spring Container is destroyed!");
}
}
@@ -0,0 +1,25 @@
package com.baeldung.shutdown.shutdown;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ShutdownController implements ApplicationContextAware {
private ApplicationContext context;
@PostMapping("/shutdownContext")
public void shutdownContext() {
((ConfigurableApplicationContext) context).close();
}
@Override
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
this.context = ctx;
}
}
@@ -0,0 +1,37 @@
package com.baeldung.toggle;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Employee {
@Id
private long id;
private double salary;
public Employee() {
}
public Employee(long id, double salary) {
this.id = id;
this.salary = salary;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
@@ -0,0 +1,7 @@
package com.baeldung.toggle;
import org.springframework.data.repository.CrudRepository;
public interface EmployeeRepository extends CrudRepository<Employee, Long> {
}
@@ -0,0 +1,12 @@
package com.baeldung.toggle;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.TYPE })
public @interface FeatureAssociation {
MyFeatures value();
}
@@ -0,0 +1,26 @@
package com.baeldung.toggle;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class FeaturesAspect {
private static final Logger LOG = LogManager.getLogger(FeaturesAspect.class);
@Around(value = "@within(featureAssociation) || @annotation(featureAssociation)")
public Object checkAspect(ProceedingJoinPoint joinPoint, FeatureAssociation featureAssociation) throws Throwable {
if (featureAssociation.value().isActive()) {
return joinPoint.proceed();
} else {
LOG.info("Feature " + featureAssociation.value().name() + " is not enabled!");
return null;
}
}
}
@@ -0,0 +1,23 @@
package com.baeldung.toggle;
import org.togglz.core.Feature;
import org.togglz.core.activation.SystemPropertyActivationStrategy;
import org.togglz.core.annotation.ActivationParameter;
import org.togglz.core.annotation.DefaultActivationStrategy;
import org.togglz.core.annotation.EnabledByDefault;
import org.togglz.core.annotation.Label;
import org.togglz.core.context.FeatureContext;
public enum MyFeatures implements Feature {
@Label("Employee Management Feature")
@EnabledByDefault
@DefaultActivationStrategy(id = SystemPropertyActivationStrategy.ID, parameters = { @ActivationParameter(name = SystemPropertyActivationStrategy.PARAM_PROPERTY_NAME, value = "employee.feature"),
@ActivationParameter(name = SystemPropertyActivationStrategy.PARAM_PROPERTY_VALUE, value = "true") })
EMPLOYEE_MANAGEMENT_FEATURE;
public boolean isActive() {
return FeatureContext.getFeatureManager().isActive(this);
}
}
@@ -0,0 +1,20 @@
package com.baeldung.toggle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class SalaryController {
@Autowired
SalaryService salaryService;
@PostMapping(value = "/increaseSalary")
@ResponseBody
public void increaseSalary(@RequestParam long id) {
salaryService.increaseSalary(id);
}
}
@@ -0,0 +1,19 @@
package com.baeldung.toggle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class SalaryService {
@Autowired
EmployeeRepository employeeRepository;
@FeatureAssociation(value = MyFeatures.EMPLOYEE_MANAGEMENT_FEATURE)
public void increaseSalary(long id) {
Employee employee = employeeRepository.findById(id).orElse(null);
employee.setSalary(employee.getSalary() + employee.getSalary() * 0.1);
employeeRepository.save(employee);
}
}
@@ -0,0 +1,15 @@
package com.baeldung.toggle;
import javax.annotation.security.RolesAllowed;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ToggleApplication {
@RolesAllowed("*")
public static void main(String[] args) {
System.setProperty("security.basic.enabled", "false");
SpringApplication.run(ToggleApplication.class, args);
}
}
@@ -0,0 +1,20 @@
package com.baeldung.toggle;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.togglz.core.manager.EnumBasedFeatureProvider;
import org.togglz.core.spi.FeatureProvider;
@Configuration
@EnableJpaRepositories("com.baeldung.toggle")
@EntityScan("com.baeldung.toggle")
public class ToggleConfiguration {
@Bean
public FeatureProvider featureProvider() {
return new EnumBasedFeatureProvider(MyFeatures.class);
}
}
@@ -0,0 +1,15 @@
package com.baeldung.webjar;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class TestController {
@GetMapping(value = "/")
public String welcome(Model model) {
return "index";
}
}
@@ -0,0 +1,12 @@
package com.baeldung.webjar;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WebjarsdemoApplication {
public static void main(String[] args) {
SpringApplication.run(WebjarsdemoApplication.class, args);
}
}
@@ -0,0 +1,14 @@
package org.baeldung.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class Application {
private static ApplicationContext applicationContext;
public static void main(String[] args) {
applicationContext = SpringApplication.run(Application.class, args);
}
}
@@ -0,0 +1,28 @@
package org.baeldung.boot.config;
import org.baeldung.boot.converter.GenericBigDecimalConverter;
import org.baeldung.boot.converter.StringToEmployeeConverter;
import org.baeldung.boot.converter.StringToEnumConverterFactory;
import org.baeldung.boot.web.resolver.HeaderVersionArgumentResolver;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addArgumentResolvers(final List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new HeaderVersionArgumentResolver());
}
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new StringToEmployeeConverter());
registry.addConverterFactory(new StringToEnumConverterFactory());
registry.addConverter(new GenericBigDecimalConverter());
}
}
@@ -0,0 +1,58 @@
package org.baeldung.boot.controller;
import org.baeldung.boot.domain.GenericEntity;
import org.baeldung.boot.domain.Modes;
import org.baeldung.boot.web.resolver.Version;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@RestController
public class GenericEntityController {
private List<GenericEntity> entityList = new ArrayList<>();
{
entityList.add(new GenericEntity(1l, "entity_1"));
entityList.add(new GenericEntity(2l, "entity_2"));
entityList.add(new GenericEntity(3l, "entity_3"));
entityList.add(new GenericEntity(4l, "entity_4"));
}
@GetMapping("/entity/all")
public List<GenericEntity> findAll() {
return entityList;
}
@PostMapping("/entity")
public GenericEntity addEntity(GenericEntity entity) {
entityList.add(entity);
return entity;
}
@GetMapping("/entity/findby/{id}")
public GenericEntity findById(@PathVariable Long id) {
return entityList.stream().filter(entity -> entity.getId().equals(id)).findFirst().get();
}
@GetMapping("/entity/findbydate/{date}")
public GenericEntity findByDate(@PathVariable("date") LocalDateTime date) {
return entityList.stream().findFirst().get();
}
@GetMapping("/entity/findbymode/{mode}")
public GenericEntity findByEnum(@PathVariable("mode") Modes mode) {
return entityList.stream().findFirst().get();
}
@GetMapping("/entity/findbyversion")
public ResponseEntity findByVersion(@Version String version) {
return version != null ? new ResponseEntity(entityList.stream().findFirst().get(), HttpStatus.OK) : new ResponseEntity(HttpStatus.NOT_FOUND);
}
}
@@ -0,0 +1,34 @@
package org.baeldung.boot.converter;
import com.google.common.collect.ImmutableSet;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.GenericConverter;
import java.math.BigDecimal;
import java.util.Set;
public class GenericBigDecimalConverter implements GenericConverter {
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
ConvertiblePair[] pairs = new ConvertiblePair[] { new ConvertiblePair(Number.class, BigDecimal.class), new ConvertiblePair(String.class, BigDecimal.class) };
return ImmutableSet.copyOf(pairs);
}
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (sourceType.getType() == BigDecimal.class) {
return source;
}
if (sourceType.getType() == String.class) {
String number = (String) source;
return new BigDecimal(number);
} else {
Number number = (Number) source;
BigDecimal converted = new BigDecimal(number.doubleValue());
return converted.setScale(2, BigDecimal.ROUND_HALF_EVEN);
}
}
}
@@ -0,0 +1,13 @@
package org.baeldung.boot.converter;
import com.baeldung.toggle.Employee;
import org.springframework.core.convert.converter.Converter;
public class StringToEmployeeConverter implements Converter<String, Employee> {
@Override
public Employee convert(String from) {
String[] data = from.split(",");
return new Employee(Long.parseLong(data[0]), Double.parseDouble(data[1]));
}
}
@@ -0,0 +1,27 @@
package org.baeldung.boot.converter;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;
@Component
public class StringToEnumConverterFactory implements ConverterFactory<String, Enum> {
private static class StringToEnumConverter<T extends Enum> implements Converter<String, T> {
private Class<T> enumType;
public StringToEnumConverter(Class<T> enumType) {
this.enumType = enumType;
}
public T convert(String source) {
return (T) Enum.valueOf(this.enumType, source.trim());
}
}
@Override
public <T extends Enum> Converter<String, T> getConverter(final Class<T> targetType) {
return new StringToEnumConverter(targetType);
}
}
@@ -0,0 +1,16 @@
package org.baeldung.boot.converter;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Component
public class StringToLocalDateTimeConverter implements Converter<String, LocalDateTime> {
@Override
public LocalDateTime convert(final String source) {
return LocalDateTime.parse(source, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}
}
@@ -0,0 +1,15 @@
package org.baeldung.boot.converter.controller;
import com.baeldung.toggle.Employee;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/string-to-employee")
public class StringToEmployeeConverterController {
@GetMapping
public ResponseEntity<Object> getStringToEmployee(@RequestParam("employee") Employee employee) {
return ResponseEntity.ok(employee);
}
}
@@ -0,0 +1,42 @@
package org.baeldung.boot.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class GenericEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String value;
public GenericEntity() {
}
public GenericEntity(String value) {
this.value = value;
}
public GenericEntity(Long id, String value) {
this.id = id;
this.value = value;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
@@ -0,0 +1,6 @@
package org.baeldung.boot.domain;
public enum Modes {
ALPHA, BETA;
}
@@ -0,0 +1,7 @@
package org.baeldung.boot.repository;
import org.baeldung.boot.domain.GenericEntity;
import org.springframework.data.jpa.repository.JpaRepository;
public interface GenericEntityRepository extends JpaRepository<GenericEntity, Long> {
}
@@ -0,0 +1,26 @@
package org.baeldung.boot.web.resolver;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import javax.servlet.http.HttpServletRequest;
@Component
public class HeaderVersionArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(final MethodParameter methodParameter) {
return methodParameter.getParameterAnnotation(Version.class) != null;
}
@Override
public Object resolveArgument(final MethodParameter methodParameter, final ModelAndViewContainer modelAndViewContainer, final NativeWebRequest nativeWebRequest, final WebDataBinderFactory webDataBinderFactory) throws Exception {
HttpServletRequest request = (HttpServletRequest) nativeWebRequest.getNativeRequest();
return request.getHeader("Version");
}
}
@@ -0,0 +1,11 @@
package org.baeldung.boot.web.resolver;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Version {
}
@@ -0,0 +1,18 @@
package org.baeldung.demo;
import com.baeldung.graphql.GraphqlConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Import;
@SpringBootApplication
@Import(GraphqlConfiguration.class)
public class DemoApplication {
public static void main(String[] args) {
System.setProperty("spring.config.name", "demo");
SpringApplication.run(DemoApplication.class, args);
}
}
@@ -0,0 +1,43 @@
package org.baeldung.demo.boottest;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Size;
@Entity
@Table(name = "person")
public class Employee {
public Employee() {
}
public Employee(String name) {
this.name = name;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Size(min = 3, max = 20)
private String name;
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;
}
}
@@ -0,0 +1,17 @@
package org.baeldung.demo.boottest;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository
@Transactional
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
public Employee findByName(String name);
public List<Employee> findAll();
}
@@ -0,0 +1,33 @@
package org.baeldung.demo.boottest;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class EmployeeRestController {
@Autowired
private EmployeeService employeeService;
@PostMapping("/employees")
public ResponseEntity<Employee> createEmployee(@RequestBody Employee employee) {
HttpStatus status = HttpStatus.CREATED;
Employee saved = employeeService.save(employee);
return new ResponseEntity<>(saved, status);
}
@GetMapping("/employees")
public List<Employee> getAllEmployees() {
return employeeService.getAllEmployees();
}
}
@@ -0,0 +1,16 @@
package org.baeldung.demo.boottest;
import java.util.List;
public interface EmployeeService {
public Employee getEmployeeById(Long id);
public Employee getEmployeeByName(String name);
public List<Employee> getAllEmployees();
public boolean exists(String email);
public Employee save(Employee employee);
}
@@ -0,0 +1,43 @@
package org.baeldung.demo.boottest;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeRepository employeeRepository;
@Override
public Employee getEmployeeById(Long id) {
return employeeRepository.findById(id).orElse(null);
}
@Override
public Employee getEmployeeByName(String name) {
return employeeRepository.findByName(name);
}
@Override
public boolean exists(String name) {
if (employeeRepository.findByName(name) != null) {
return true;
}
return false;
}
@Override
public Employee save(Employee employee) {
return employeeRepository.save(employee);
}
@Override
public List<Employee> getAllEmployees() {
return employeeRepository.findAll();
}
}
@@ -0,0 +1,21 @@
package org.baeldung.demo.components;
import org.baeldung.demo.model.Foo;
import org.baeldung.demo.repository.FooRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class FooService {
@Autowired
private FooRepository fooRepository;
public Foo getFooWithId(Integer id) throws Exception {
return fooRepository.findById(id).orElse(null);
}
public Foo getFooWithName(String name) {
return fooRepository.findByName(name);
}
}
@@ -0,0 +1,13 @@
package org.baeldung.demo.exceptions;
public class CommonException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 3080004140659213332L;
public CommonException(String message) {
super(message);
}
}
@@ -0,0 +1,13 @@
package org.baeldung.demo.exceptions;
public class FooNotFoundException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 9042200028456133589L;
public FooNotFoundException(String message) {
super(message);
}
}
@@ -0,0 +1,45 @@
package org.baeldung.demo.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Foo implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Integer id;
private String name;
public Foo() {
}
public Foo(String name) {
this.name = name;
}
public Foo(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,8 @@
package org.baeldung.demo.repository;
import org.baeldung.demo.model.Foo;
import org.springframework.data.jpa.repository.JpaRepository;
public interface FooRepository extends JpaRepository<Foo, Integer> {
public Foo findByName(String name);
}
@@ -0,0 +1,26 @@
package org.baeldung.demo.service;
import org.baeldung.demo.components.FooService;
import org.baeldung.demo.model.Foo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class FooController {
@Autowired
private FooService fooService;
@GetMapping("/{id}")
public Foo getFooWithId(@PathVariable Integer id) throws Exception {
return fooService.getFooWithId(id);
}
@GetMapping("/")
public Foo getFooWithName(@RequestParam String name) throws Exception {
return fooService.getFooWithName(name);
}
}