Skip to content

Commit 8941856

Browse files
committed
Search Employee By Id implemented
1 parent 0bf021a commit 8941856

File tree

2 files changed

+27
-8
lines changed

2 files changed

+27
-8
lines changed

src/main/java/com/itacademy/CrudEmpleats/controller/ControllerEmployees.java

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,17 @@
22

33
import java.io.IOException;
44
import java.util.List;
5+
import java.util.NoSuchElementException;
56

67
import javax.servlet.http.HttpServletResponse;
78

89
import org.springframework.beans.factory.annotation.Autowired;
10+
import org.springframework.http.HttpStatus;
911
import org.springframework.web.bind.annotation.GetMapping;
12+
import org.springframework.web.bind.annotation.PathVariable;
13+
import org.springframework.web.bind.annotation.ResponseStatus;
1014
import org.springframework.web.bind.annotation.RestController;
15+
import org.springframework.web.server.ResponseStatusException;
1116

1217
import com.itacademy.CrudEmpleats.domain.Employee;
1318
import com.itacademy.CrudEmpleats.persistence.EmployeeRepository;
@@ -36,16 +41,25 @@ public class ControllerEmployees {
3641

3742
//Temporalment redirigim a la llista d'empleats
3843
@GetMapping("/")
39-
void start(HttpServletResponse reponse) throws IOException{
40-
reponse.sendRedirect("/Empleat");;
44+
void start(HttpServletResponse reponse) throws IOException {
45+
reponse.sendRedirect("/Empleat");
4146
}
42-
43-
//Retorna una llista JSon d'empleats
47+
48+
// Retorna una llista JSon d'empleats
4449
@GetMapping("/Empleat")
45-
public List<Employee> allEmployees(){
50+
public List<Employee> allEmployees() {
4651
return repositori.getAllEmployees();
4752
}
48-
49-
53+
54+
// Busca un empleat per Id
55+
@GetMapping("/Empleat/{id}")
56+
public Employee getEmployee(@PathVariable("id") int id) {
57+
try {
58+
return repositori.getEmployeeById(id);
59+
} catch (NoSuchElementException e) {
60+
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "No s'ha trobat cap empleat amb el id =" + id);
61+
}
62+
63+
}
5064

5165
}

src/main/java/com/itacademy/CrudEmpleats/persistence/EmployeeRepository.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,18 @@ public class EmployeeRepository {
1616

1717
private List<Employee> repository = new ArrayList<>(
1818
Arrays.asList(
19-
new Employee("Juan", "Director de Projectes"),
19+
new Employee("Joan", "Director de Projectes"),
2020
new Employee("Gerard", "Programador"),
2121
new Employee("Maria", "Administrativa")
2222
)
2323
);
24+
2425
public List<Employee> getAllEmployees() {
2526
return repository;
2627
}
28+
29+
public Employee getEmployeeById(int id) throws NoSuchElementException{
30+
return repository.stream().filter(employee -> employee.getId()==id).findFirst().get();
31+
}
2732

2833
}

0 commit comments

Comments
 (0)