Commit 74fb4b93 authored by earndt's avatar earndt

[W5D2] (ArndtED) Adds Spring Boot assignment

parent 7b39150f
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
# Directories #
/build/
bin/
repos/
/repos/
doc/
/doc/
.gradle/
/bin/
target/
# OS Files #
.DS_Store
# JetBrain's Idea specific stuff #
.idea*
*.iml
# User-specific stuff:
.idea/workspace.xml
.idea/tasks.xml
.idea/dictionaries
.idea/vcs.xml
.idea/jsLibraryMappings.xml
# Sensitive or high-churn files:
.idea/dataSources.ids
.idea/dataSources.xml
.idea/dataSources.local.xml
.idea/sqlDataSources.xml
.idea/dynamic.xml
.idea/uiDesigner.xml
# Gradle:
.idea/gradle.xml
.idea/libraries
# Mongo Explorer plugin:
.idea/mongoSettings.xml
## File-based project format:
*.iws
## Plugin-specific files:
# IntelliJ
/out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
*.class
browscap.csv
gradle/wrapper
gradlew.bat
gradlew
# Package Files #
*.jar
*.war
*.ear
*.db
######################
# Windows
######################
# Windows image file caches
Thumbs.db
# Folder config file
Desktop.ini
######################
# OSX
######################
.DS_Store
.svn
# Thumbnails
._*
# Files that might appear on external disk
.Spotlight-V100
.Trashes
######################
# Eclipse
######################
*.pydevproject
.project
.metadata
bin/**
tmp/**
tmp/**/*
*.tmp
*.bak
*.swp
*~.nib
local.properties
.classpath
.settings/
.loadpath
/src/main/resources/rebel.xml
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# CDT-specific
.cproject
# PDT-specific
.buildpath
plugins {
id 'org.springframework.boot' version '2.4.4'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.nisum'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'junit:junit:4.12'
runtimeOnly 'com.h2database:h2'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
test {
useJUnitPlatform()
}
rootProject.name = 'employeeservice'
package com.nisum.employeeservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EmployeeserviceApplication {
public static void main(String[] args) {
SpringApplication.run(EmployeeserviceApplication.class, args);
}
}
package com.nisum.employeeservice.aspect;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LoggingAspect {
private final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);
// @Before("execution(* EmployeeService.findAllEmployees())")
// public void logBefore() {
// logger.info("{} before advice", "Logger");
// logger.error("Fake Error");
// }
}
package com.nisum.employeeservice.controller;
import com.nisum.employeeservice.model.Employee;
import com.nisum.employeeservice.service.EmployeeService;
import com.nisum.employeeservice.exception.ResourceNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/api/v1")
public class EmployeeController {
@Autowired
EmployeeService employeeService;
//read all
@GetMapping("/employees")
public List<Employee> getAllEmployees(){
return employeeService.findAllEmployees();
}
//read one
@GetMapping("/employees/{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable("id") Long employeeId) throws ResourceNotFoundException {
Employee employee = employeeService.getEmployeeById(employeeId)
.orElseThrow(()-> new ResourceNotFoundException("Employee by Id not found." + employeeId));
return ResponseEntity.ok().body(employee);
}
//create
@PostMapping("/employees")
public Employee createEmployee(@RequestBody Employee employee){
return employeeService.addEmployee(employee);
}
//update
@PutMapping("/employees/{id}")
public ResponseEntity<Employee> updateEmployee(@PathVariable("id") Long employeeId, @RequestBody @Valid Employee newEmployee) throws ResourceNotFoundException{
Employee oldEmployee = employeeService.getEmployeeById(employeeId)
.orElseThrow(()-> new ResourceNotFoundException("Could not find employee with that Id." + employeeId));
employeeService.updateEmployee(oldEmployee, newEmployee);
return ResponseEntity.ok().body(newEmployee);
}
//destroy
@DeleteMapping("/employees/{id}")
public ResponseEntity<Employee> deleteEmployee(@PathVariable("id") Long employeeId) throws ResourceNotFoundException{
Employee employee = employeeService.getEmployeeById(employeeId)
.orElseThrow(()-> new ResourceNotFoundException("No employee by that name." + employeeId));
employeeService.deleteEmployee(employee);
return ResponseEntity.ok().body(employee);
}
}
package com.nisum.employeeservice.exception;
import java.util.Date;
public class ErrorDetails {
private Date timestamp;
private String message;
private String details;
public ErrorDetails(Date timestamp, String message, String details) {
this.timestamp = timestamp;
this.message = message;
this.details = details;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
}
package com.nisum.employeeservice.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import java.util.Date;
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
public ResponseEntity<?> resourceNotFoundException(ResourceNotFoundException ex, WebRequest webRequest){
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), webRequest.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
}
}
package com.nisum.employeeservice.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends Exception {
public ResourceNotFoundException(String message){
super(message);
}
}
package com.nisum.employeeservice.model;
import javax.persistence.*;
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
public Employee(){}
public Employee(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public String getFirstName() {
return firstName;
}
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
package com.nisum.employeeservice.repository;
import com.nisum.employeeservice.model.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
package com.nisum.employeeservice.service;
import com.nisum.employeeservice.model.Employee;
import com.nisum.employeeservice.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class EmployeeService {
@Autowired
EmployeeRepository employeeRepository;
public List<Employee> findAllEmployees(){
return employeeRepository.findAll();
}
public Employee addEmployee(Employee employee){
return employeeRepository.save(employee);
}
public Optional<Employee> getEmployeeById(Long employeeId) {
return employeeRepository.findById(employeeId);
}
public void deleteEmployee(Employee employee) {
employeeRepository.delete(employee);
}
public Employee updateEmployee(Employee oldEmployee, Employee newEmployee){
oldEmployee.setId(newEmployee.getId());
oldEmployee.setFirstName(newEmployee.getFirstName());
oldEmployee.setLastName(newEmployee.getLastName());
Employee updatedEmployee = employeeRepository.save(oldEmployee);
return updatedEmployee;
}
}
spring.datasource.url=jdbc:h2:mem:dataSource
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.schema=classpath:employee.sql
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=none
spring.h2.console.enabled=true
management.endpoint.beans.enabled=true
management.endpoints.web.exposure.include=*
info.app.name=Employee Service Application Actuator
\ No newline at end of file
DROP TABLE IF EXISTS EMPLOYEE;
CREATE TABLE EMPLOYEE (
ID INT AUTO_INCREMENT PRIMARY KEY,
FIRST_NAME VARCHAR (255) NOT NULL,
LAST_NAME VARCHAR (255) NOT NULL
);
INSERT INTO EMPLOYEE VALUES (1, 'Eric', 'Arndt'), (2, 'Erica', 'Brandt'), (3, 'Guy', 'Incognito');
\ No newline at end of file
package com.nisum.employeeservice;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class EmployeeserviceApplicationTests {
@Test
void contextLoads() {
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment